package com.second.app.thread.reentrant.trylock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author gyz
 * @date 2021/2/2 16:51
 */
public class MyService {
    private ReentrantLock reentrantLock = new ReentrantLock();

    private Condition newCondition = reentrantLock.newCondition();

    public void testMethod() {
        try {
            if (reentrantLock.tryLock()) {
                System.out.println(Thread.currentThread().getName() + "：拿到锁了");
                newCondition.await();
                System.out.println(Thread.currentThread().getName() + "：不等了，开始上路了");
            } else {
                System.out.println(Thread.currentThread().getName() + "：没拿到锁");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            reentrantLock.unlock();
            System.out.println(Thread.currentThread().getName() + "：释放锁了");
        }
    }

    /**
     * 唤醒绑定此condition的线程
     */
    public void wakeup() {
        reentrantLock.lock();
        try {
            System.out.println(Thread.currentThread().getName()+"：唤醒绑定此condition的线程");
            newCondition.signalAll();
        } finally {
            reentrantLock.unlock();
        }
    }
}
